package offer;

public class Offer12 {

    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        boolean res = false;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                res=dfs(board,words,i,j,0);
                //todo：我能从一个位置出发找到满足条件的结果
                if (res==true){
                    return  true;
                }
            }
        }
        return  res;
    }


    public boolean  dfs(char[][] board,char[]  words,int i,int j,int k){
        if (i<0||i> board.length-1||j<0||j> board[0].length-1||board[i][j]!=words[k]||k> words.length-1){
            return false;
        }
        if (k== words.length-1){
            return  true;
        }
        boolean res;
        board[i][j]='\0';
//        todo: 不正确的dfs  直接就返回false了  其他的满足的 最后才回溯返回结果   才能一直往下递归调用
        res=dfs(board,words,i-1,j,k+1)||
                dfs(board,words,i+1,j,k+1) ||
                dfs(board,words,i,j-1,k+1)||dfs(board,words,i,j+1,k+1);
        board[i][j]=words[k];
         return  res;
    }



    public static void main(String[] args) {
    char[][]    board ={{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
        Offer12 offer12 = new Offer12();
        System.out.println(offer12.exist(board, "ABCCED"));

    }

}
